package com.example.demoddd.domain.userauth.handler;

import cn.hutool.json.JSONUtil;
import com.example.demoddd.application.dto.Results;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

/**
 * 权限不足 拒绝访问 handler
 */
@Slf4j
public class AuthLimitHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.error("没有权限访问该URL,{}", e.getMessage(), e);

        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.SC_FORBIDDEN);
        Results results = new Results();
        results.setCode(403);
        results.setMsg("没有权限访问该URL");
        response.getWriter().write(JSONUtil.toJsonStr(results));
    }

}

